//
//  AITools.m
//  AssetsInventory
//
//  Created by 李沛池 on 2017/11/30.
//  Copyright © 2017年 李沛池. All rights reserved.
//

#import "AITools.h"
#import "Reachability.h"
#import <AVFoundation/AVFoundation.h>

@implementation AITools

//只有一个取消按钮的提示框
+ (void)showAlertWithVC:(UIViewController *)vc title:(NSString *)title message:(NSString *)message cancelText:(NSString *)cancelText
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelText style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    
    [alertController addAction:cancelAction];
    
    [vc presentViewController:alertController animated:YES completion:nil];
}

//网络连接状态
+ (BOOL)networkStatus
{
    Reachability *hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([hostReach currentReachabilityStatus]) {
        case NotReachable:
            // 没有网络连接
            return NO;
            break;
        case ReachableViaWWAN:
            // 使用3G网络
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            break;
    }
    return YES;
}

/** 打开手电筒 */
+ (void)openFlashlight
{
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    if ([captureDevice hasTorch]) {
        BOOL locked = [captureDevice lockForConfiguration:&error];
        if (locked) {
            captureDevice.torchMode = AVCaptureTorchModeOn;
            [captureDevice unlockForConfiguration];
        }
    }
}
/** 关闭手电筒 */
+ (void)closeFlashlight
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        [device setTorchMode: AVCaptureTorchModeOff];
        [device unlockForConfiguration];
    }
}

//保存下载的文件（根据格式 array或dic）
+ (BOOL)saveFileWithFileName:(NSString *)fileName data:(id)data folderPath:(NSString *)folderPath
{
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if(![fm fileExistsAtPath:folderPath]){
        [fm createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //文件存放路径
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    //如果文件已存在则覆盖
    if ([fm fileExistsAtPath:filePath]) {
        [fm removeItemAtPath:filePath error:nil];
    }
    //写入文件
    if ([data isKindOfClass:[NSArray class]]) {
        NSData * dataArray = [NSKeyedArchiver archivedDataWithRootObject:data];
        return [dataArray writeToFile:filePath atomically:YES];
    }
    return [data writeToFile:filePath atomically:YES];
}

//获取目录下所有文件
+ (NSArray*)allFilesAtPath:(NSString*)dirString
{
    NSMutableArray* array = [NSMutableArray arrayWithCapacity:10];
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSArray* tempArray = [fileMgr contentsOfDirectoryAtPath:dirString error:nil];
    for (NSString* fileName in tempArray) {
        BOOL flag = YES;
        NSString* fullPath = [dirString stringByAppendingPathComponent:fileName];
        if ([fileMgr fileExistsAtPath:fullPath isDirectory:&flag]) {
            if (!flag) {
                [array addObject:fullPath];
            }
        }
    }
    return array;
}

//获取目录下所有文件名
+ (NSArray*)allFileNamesAtPath:(NSString*)dirString
{
    return [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dirString error:nil];
}

//删除目录下所有文件
+ (void)removeAllFilesAtPath:(NSString*)dirString
{
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    for (NSString *path in [fileMgr contentsOfDirectoryAtPath:dirString error:nil]) {
        [fileMgr removeItemAtPath:[dirString stringByAppendingPathComponent:path] error:nil];
    }
}

//JSON串转成Object对象
+ (id)jsonStringToObject:(NSString *)jsonStr
{
    if (![jsonStr isKindOfClass:[NSString class]]) {
        return jsonStr;
    }
    NSData *dataJSON = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObj = [NSJSONSerialization JSONObjectWithData:dataJSON
                                                 options:kNilOptions
                                                   error:nil];
    return jsonObj;
}

//转换成JSON串字符串（没有可读性）
+ (NSString *)objectToJSONString:(id)object
{
    if (!object) {
        return @"";
    }
//    NSString *str = [[NSString alloc] initWithData:object encoding:NSUTF8StringEncoding];
//    return  str;
    //e.g. : [{"key":"value"},{"key":"value"}]
    NSData *data = [NSJSONSerialization dataWithJSONObject:object options:NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments error:nil];
    if (data == nil) return @"";
    return  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//转换成JSON串字符串（有可读性）
+ (NSString *)objectToReadableJSONString:(id)object
{
    /*e.g. :
     [
      {
      "key" : "value"
      },
      {
      "key" : "value"
      }
     ]
     */
    NSData *data = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:nil];
    if (data == nil) return @"";
    return  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//转换成JSON数据
+ (NSData *)objectToJSONData:(id)object
{
    //e.g. : <5b0a2020 7b0a2020 2020226b 65792220 3a202276 616c7565 220a2020 7d2c0a20 207b0a20 20202022 6b657922 203a2022 76616c75 65220a20 207d0a5d>
    return [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:nil];
}

@end

